package org.lpw.wormhole;

import org.lpw.wormhole.cache.CacheFactoryImpl;
import org.lpw.wormhole.queue.QueueFactoryImpl;
import org.lpw.wormhole.scheduler.MinuteJob;
import org.lpw.wormhole.scheduler.MinuteTimer;
import org.lpw.wormhole.util.Kit;
import org.lpw.wormhole.util.KitImpl;

/**
 * Wormhole系统上下文环境。
 * 
 * @author lpw
 */
public class SimpleWormholeContext
    implements WormholeContext
{
    protected Kit kit;
    protected MinuteTimer minuteTimer;
    protected Thread minuteTimerThread;

    @Override
    public void initialize()
    {
        kit = new KitImpl();
        WormholeManager.getInstance().setWormholeContext(this);
        WormholeManager.getInstance().setCacheFactory(new CacheFactoryImpl(kit));
        WormholeManager.getInstance().setQueueFactory(new QueueFactoryImpl(kit));
        WormholeManager.getInstance().setKit(kit);

        minuteTimer = new MinuteTimer();
        minuteTimer.addMinuteJob((MinuteJob)WormholeManager.getInstance().getCacheFactory().getLocalCache());
        minuteTimerThread = new Thread(minuteTimer);
        minuteTimerThread.start();

        if(kit.getLogger().isInfoEnable())
            kit.getLogger().info("初始化Wormhole系统完成！");
    }

    @Override
    public void destory()
    {
        minuteTimer.exit();
        minuteTimerThread.interrupt();
        kit.getHttp().destory();
        WormholeManager.getInstance().getQueueFactory().getLocalQueue().destory();

        if(kit.getLogger().isInfoEnable())
            kit.getLogger().info("销毁Wormhole系统完毕！");
    }
}
